package com.example.demo.utils;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ASMUtils {
    public static Set<String> analyzeClassDependencies(Path classFile) throws IOException {
        Set<String> dependencies = new HashSet<>();

        ClassReader classReader = new ClassReader(Files.newInputStream(classFile));
        classReader.accept(new ClassVisitor(Opcodes.ASM9) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
                return new MethodVisitor(Opcodes.ASM9) {
                    @Override
                    public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) {
                        dependencies.add(owner.replace('/', '.'));
                    }
                };
            }
        }, 0);

        return dependencies;
    }

    public static Map<String, Set<String>> analyzeJarDependencies(Path jarFile) throws IOException {
        Map<String, Set<String>> dependencies = new HashMap<>();

        try (JarFile jar = new JarFile(jarFile.toFile())) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (entry.getName().endsWith(".class")) {
                    try (var inputStream = jar.getInputStream(entry)) {
                        Set<String> classDependencies = new HashSet<>();
                        ClassReader classReader = new ClassReader(inputStream);
                        classReader.accept(new ClassVisitor(Opcodes.ASM9) {
                            @Override
                            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
                                return new MethodVisitor(Opcodes.ASM9) {
                                    @Override
                                    public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) {
                                        classDependencies.add(owner.replace('/', '.'));
                                    }
                                };
                            }
                        }, 0);
                        dependencies.put(entry.getName(), classDependencies);
                    }
                }
            }
        }

        return dependencies;
    }
<<<<<<< HEAD
}
=======
}
>>>>>>> ae04cf21c481035528eaf247571d600f597507d9
